package sapling.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sapling.aop.WebLogAspect;
import sapling.dao.AdminDao;
import sapling.dao.LogDao;
import sapling.dao.RoleDao;
import sapling.dao.UserDao;
import sapling.model.Admin;
import sapling.model.Log;
import sapling.model.Role;
import sapling.model.User;
import sapling.utils.Md5Util;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * Created by Administrator on 2017/6/21.
 */
@Service
@Transactional
public class UserService {


    @Autowired
    UserDao userDao;
    @Autowired
    AdminDao adminDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    RoleService roleService;

    /**
     * 保存用户
     */
    public void save(String username,String password) {
        Subject currentUser = SecurityUtils.getSubject();
        String usernames = currentUser.getSession().getAttribute("username").toString();
        if (Objects.nonNull(username)&&username.length()>0&&Objects.nonNull(password)&&password.length()>0){
            User user= userDao.findOneByUsername(username);
            if(Objects.isNull(user)){
                User user1=new User();
                user1.setUsername(username);
                user1.setPassword(Md5Util.getMd5(password));
                if(Objects.nonNull(usernames)&&usernames.length()>0){
                    Admin admin=adminDao.findOneByUsername(usernames);
                    if(Objects.nonNull(admin)&&Objects.nonNull(admin.getCompany())){
                        user1.setCompany(admin.getCompany());
                        userDao.save(user1);
                        Role role= roleDao.findOneByName("common");//新用户默认是普通操作员
                        roleService.saveRole(role.getRole_id(),user1.getUser_id());
                    }
                }
            }
        }
    }
}
